import general.GlobalProperties;

import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.io.File;
import java.util.Timer;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;

import serverHandling.HttpRequestHandlers;
import systemFile.FileWatcher;
import systemFile.Schedule;
import systemFile.ScheduleSyncAlgorithm;
import systemFile.SysTray;

public class RunProgram {
    static FileWatcher fileWatcher;

    public static void main(String[] args) throws Exception {
	Timer timer = new Timer();
	timer.schedule(new Schedule(), 0, GlobalProperties.getTimer());

	TrayIcon icon = new TrayIcon(SysTray.getImage(), "File watcher",
		SysTray.createPopupMenu());
	SystemTray.getSystemTray().add(icon);

	FileSystemManager fsManager;
	fileWatcher = new FileWatcher(icon);
	HttpRequestHandlers.initialSynchronization();

	/*
	 * algorytm synchronizujacy uruchamiany co 2 minuty
	 */
	if (GlobalProperties.isLogged) {
	    Timer timerSync = new Timer();
	    timerSync.schedule(new ScheduleSyncAlgorithm(), 120000, 120000);
	}

	try {
	    fsManager = VFS.getManager();
	    // sciezka do monitorowanego folderu z plikami
	    FileObject listendir = fsManager
		    .resolveFile(GlobalProperties.properties.get(
			    GlobalProperties.FOLDER_MONIT).toString());
	    DefaultFileMonitor fm = new DefaultFileMonitor(fileWatcher);

	    fm.setRecursive(true);
	    fm.addFile(listendir);

	    fm.start();
	    fm.run();
	} catch (FileSystemException e) {
	    e.printStackTrace();
	} finally {
	    HttpRequestHandlers.logout();
	}
    }

    public static File getSettingsDirectory() {
	String userHome = System.getProperty("user.home");
	if (userHome == null) {
	    throw new IllegalStateException("user.home==null");
	}
	File home = new File(userHome);
	File settingsDirectory = new File(home, ".myappdir");
	if (!settingsDirectory.exists()) {
	    if (!settingsDirectory.mkdir()) {
		throw new IllegalStateException(settingsDirectory.toString());
	    }
	}
	return settingsDirectory;
    }
}